<script setup>
import { ref } from 'vue'
import { User, Lock, Iphone, Message, Plus, UserFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { userStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
import http from "@/utils/http.js";

const isRegister = ref(false)
const loading = ref(false)
const form = ref() // 表单引用
const router = useRouter()
const uStore = userStore()

// 表单数据
const loginUser = ref({
  userUsername: '',
  userPassword: ''
})

const registerUser = ref({
  userNickname: '',
  userUsername: '',
  userPassword: '',
  rePassword: '',
  userPhone: '',
  userEmail: '',
  userAvatar: '',
})

// 密码一致性校验
const checkRePassword = (rule, value, callback) => {
  if (value !== registerUser.value.userPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 校验规则
const rules = {
  userNickname: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {min: 1, max: 20, message: '长度为1 ~ 20位非空字符', trigger: 'blur'}
  ],
  userUsername: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5 ~ 16位非空字符', trigger: 'blur'}
  ],
  userPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5 ~ 16位非空字符', trigger: 'blur'}
  ],
  rePassword: [
    {validator: checkRePassword, trigger: 'blur'}
  ],
  userPhone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {min: 11, max: 11, message: '请输入正确手机号格式', trigger: 'blur'}
  ],
  userEmail: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {min: 5, max: 20, message: '长度为5 ~ 20位非空字符', trigger: 'blur'}
  ]
}



// 头像上传成功处理
const handleAvatarSuccess = (res) => {
  registerUser.value.userAvatar = res.data
  ElMessage.success('头像上传成功')
}

// 登录方法
const login = async () => {
  try {
    loading.value = true
    await form.value.validate()
    await uStore.getUserInfo(loginUser.value)
    
    if (uStore.userInfo?.code === 666) {
      ElMessage.success('登录成功')
      const path = uStore.userInfo.data.userType === 2 ? '/admin' : '/user'
      await router.replace(path)
    }
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    loading.value = false
  }
}

// 注册方法
const register = async () => {
  try {
    loading.value = true
    await form.value.validate()
    
    const res = await http.post('/users/register', registerUser.value)
    if (res.code === 666) {
      ElMessage.success('注册成功')
      isRegister.value = false
      clearRegisterData()
    }
  } catch (error) {
    console.error('注册失败:', error)
  } finally {
    loading.value = false
  }
}

// 清空注册数据
const clearRegisterData = () => {
  registerUser.value = {
    userNickname: '',
    userUsername: '',
    userPassword: '',
    rePassword: '',
    userPhone: '',
    userEmail: '',
    userAvatar: '',
  }
}

// 切换登录/注册
const toggleForm = () => {
  isRegister.value = !isRegister.value
  form.value?.clearValidate()
}
</script>

<template>
  <div class="login-container">
    <div class="background-image"></div>
    
    <div class="form-wrapper">
      <el-card class="login-card">
        <h2 class="title">{{ isRegister ? '用户注册' : '系统登录' }}</h2>
        
        <!-- 注册表单 -->
        <el-form 
          v-if="isRegister"
          ref="form"
          :model="registerUser" 
          :rules="rules"
          @keyup.enter="register"
        >
          <el-form-item prop="userNickname">
            <el-input
              v-model="registerUser.userNickname"
              placeholder="请输入昵称"
              :prefix-icon="UserFilled"
            />
          </el-form-item>
          
          <el-form-item prop="userUsername">
            <el-input
              v-model="registerUser.userUsername"
              placeholder="请输入用户名"
              :prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="userPassword">
            <el-input
              v-model="registerUser.userPassword"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              type="password"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="rePassword">
            <el-input
              v-model="registerUser.rePassword"
              placeholder="请确认密码"
              :prefix-icon="Lock"
              type="password"
            />
          </el-form-item>
          
          <el-form-item prop="userPhone">
            <el-input
              v-model="registerUser.userPhone"
              placeholder="请输入手机号"
              :prefix-icon="Iphone"
            />
          </el-form-item>
          
          <el-form-item prop="userEmail">
            <el-input
              v-model="registerUser.userEmail"
              placeholder="请输入邮箱"
              :prefix-icon="Message"
            />
          </el-form-item>
          
          <el-form-item prop="userAvatar">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="registerUser.userAvatar" :src="registerUser.userAvatar" class="avatar">
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <span class="upload-text">点击上传头像</span>
            </el-upload>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              class="submit-btn"
              @click="register"
              :loading="loading"
            >
              立即注册
            </el-button>
          </el-form-item>
          
          <el-form-item class="footer">
            <el-link type="info" :underline="false" @click="toggleForm">
              ← 返回登录
            </el-link>
          </el-form-item>
        </el-form>
        
        <!-- 登录表单 -->
        <el-form 
          v-else
          ref="form"
          :model="loginUser" 
          :rules="rules"
          @keyup.enter="login"
        >
          <el-form-item prop="userUsername">
            <el-input
              v-model="loginUser.userUsername"
              placeholder="请输入用户名"
              :prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="userPassword">
            <el-input
              v-model="loginUser.userPassword"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              type="password"
              show-password
            />
          </el-form-item>
          
          <el-form-item class="remember">
            <el-checkbox>记住密码</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              class="submit-btn"
              @click="login"
              :loading="loading"
            >
              立即登录
            </el-button>
          </el-form-item>
          
          <el-form-item class="footer">
            <el-link type="info" :underline="false" @click="toggleForm">
              没有账号？立即注册 →
            </el-link>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.background-image {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/images/image.png');
  background-size: cover;
  background-position: center;
  filter: brightness(0.7);
  z-index: 1;
}

.form-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  z-index: 2;
}

.login-card {
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.submit-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

.remember {
  display: flex;
  justify-content: space-between;
}

.footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
}

.upload-text {
  margin-top: 8px;
  color: #666;
}

@media (max-width: 768px) {
  .form-wrapper {
    width: 90%;
  }
  
  .login-card {
    padding: 20px;
  }
}
</style>